package com.wyix.service.impl;

import com.wyix.exception.AuthException;
import com.wyix.properties.AuthProperties;
import com.wyix.service.AuthService;
import com.wyix.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * 权限认证服务实现类
 */
public class AuthServiceImpl implements AuthService {
    private final AuthProperties authProperties;

    @Autowired
    public AuthServiceImpl(AuthProperties authProperties) {
        this.authProperties = authProperties;
    }

    @Override
    public boolean verifyToken(String token) {
        if (token == null || token.isEmpty()) {
            throw new AuthException("Token不能为空");
        }

        // 检查Token格式是否正确
        if (!TokenUtils.isValidTokenFormat(token, authProperties.getSecret())) {
            throw new AuthException("无效的Token格式");
        }

        try {
            String username = TokenUtils.extractUsername(token, authProperties.getSecret());
            return TokenUtils.validateToken(token, username, authProperties.getSecret());
        } catch (RuntimeException e) {
            throw new AuthException("Token验证失败: " + e.getMessage());
        }
    }

    @Override
    public String generateToken(String username) {
        return generateToken(username, null);
    }

    @Override
    public String generateToken(String username, Map<String, Object> claims) {
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        long expirationMillis = authProperties.getTokenExpireTime().toMillis();
        return TokenUtils.generateToken(username, authProperties.getSecret(), expirationMillis, claims);
    }

    @Override
    public String generateRefreshToken(String username) {
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        long expirationMillis = authProperties.getRefreshTokenExpireTime().toMillis();
        return TokenUtils.generateToken(username, authProperties.getSecret(), expirationMillis, null);
    }

    @Override
    public String getUsernameFromToken(String token) {
        if (token == null || token.isEmpty()) {
            throw new AuthException("Token不能为空");
        }

        try {
            return TokenUtils.extractUsername(token, authProperties.getSecret());
        } catch (RuntimeException e) {
            throw new AuthException("从Token中提取用户名失败: " + e.getMessage());
        }
    }

    @Override
    public String refreshToken(String refreshToken) {
        if (!verifyToken(refreshToken)) {
            throw new AuthException("刷新Token无效");
        }

        String username = getUsernameFromToken(refreshToken);
        return generateToken(username);
    }
}
